#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OpenVPN 监控系统启动脚本
"""

import os
import sys
import socket
import time
from datetime import datetime

def check_openvpn_connection(host, port, password):
    """检查OpenVPN管理接口连接"""
    print(f"正在检查OpenVPN管理接口连接...")
    print(f"服务器: {host}:{port}")
    
    try:
        # 创建socket连接
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(10)
        sock.connect((host, port))
        
        # 持续读取直到出现ENTER PASSWORD或SUCCESS
        response = recv_until(sock, ["ENTER PASSWORD", "SUCCESS"], 10)
        print(f"收到响应: {response.strip()}")
        
        if 'ENTER PASSWORD' in response:
            # 发送密码
            sock.send((password + '\n').encode('utf-8'))
            response = recv_until(sock, ["SUCCESS", "ERROR"], 10)
            print(f"密码验证响应: {response.strip()}")
            
            if 'SUCCESS' in response:
                print("✅ OpenVPN管理接口连接成功！")
                sock.close()
                return True
            else:
                print("❌ 密码验证失败")
                sock.close()
                return False
        elif 'SUCCESS' in response:
            print("✅ OpenVPN管理接口连接成功！")
            sock.close()
            return True
        else:
            print("❌ 未收到密码提示")
            sock.close()
            return False
            
    except socket.timeout:
        print("❌ 连接超时")
        return False
    except ConnectionRefusedError:
        print("❌ 连接被拒绝，请检查OpenVPN服务器是否运行")
        return False
    except Exception as e:
        print(f"❌ 连接错误: {e}")
        return False

def recv_until(sock, end_markers, timeout=10):
    """
    持续读取socket直到遇到end_markers中的任意一个字符串或超时
    """
    sock.settimeout(timeout)
    data = b''
    start_time = time.time()
    while True:
        try:
            chunk = sock.recv(4096)
            if not chunk:
                break
            data += chunk
            text = data.decode('utf-8', errors='ignore')
            for marker in end_markers:
                if marker in text:
                    return text
            if time.time() - start_time > timeout:
                break
        except socket.timeout:
            break
        except Exception as e:
            print(f"读取数据异常: {e}")
            break
    return data.decode('utf-8', errors='ignore')

def check_dependencies():
    """检查Python依赖"""
    print("检查Python依赖...")
    
    try:
        import flask
        print(f"✅ Flask {flask.__version__}")
    except ImportError:
        print("❌ Flask未安装，请运行: pip install -r requirements.txt")
        return False
    
    try:
        import sqlite3
        print("✅ SQLite3")
    except ImportError:
        print("❌ SQLite3未安装")
        return False
    
    return True

def create_directories():
    """创建必要的目录"""
    directories = ['templates', 'static/css', 'static/js']
    
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print(f"✅ 创建目录: {directory}")

def main():
    """主函数"""
    print("=" * 50)
    print("OpenVPN 监控系统启动器")
    print("=" * 50)
    print(f"启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    # 检查依赖
    if not check_dependencies():
        print("\n请安装缺失的依赖后重试")
        sys.exit(1)
    
    # 创建目录
    create_directories()
    
    # 从app.py导入配置
    try:
        from app import OPENVPN_HOST, OPENVPN_PORT, OPENVPN_PASSWORD
    except ImportError as e:
        print(f"❌ 无法导入配置: {e}")
        print("请确保app.py文件存在且配置正确")
        sys.exit(1)
    
    # 检查OpenVPN连接
    if not check_openvpn_connection(OPENVPN_HOST, OPENVPN_PORT, OPENVPN_PASSWORD):
        print("\n⚠️  OpenVPN连接检查失败，但程序仍将启动")
        print("请检查以下配置:")
        print(f"   - 服务器IP: {OPENVPN_HOST}")
        print(f"   - 端口: {OPENVPN_PORT}")
        print(f"   - 密码: {OPENVPN_PASSWORD}")
        print("   - OpenVPN服务器是否运行")
        print("   - management接口是否开启")
        print()
        
        response = input("是否继续启动程序? (y/N): ")
        if response.lower() != 'y':
            print("程序已取消")
            sys.exit(0)
    
    print("\n" + "=" * 50)
    print("启动OpenVPN监控系统...")
    print("=" * 50)
    
    # 启动Flask应用
    try:
        from app import app
        print("✅ Flask应用启动成功")
        print(f"🌐 访问地址: http://localhost:5000")
        print("按 Ctrl+C 停止程序")
        print()
        
        app.run(debug=True, host='0.0.0.0', port=5000)
        
    except KeyboardInterrupt:
        print("\n\n程序已停止")
    except Exception as e:
        print(f"\n❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main() 